<?php
namespace app\common\service;
use GuzzleHttp\Exception\RequestException;

class Logistics
{
    const TYPE = [
        'yuantong'=>'圆通速递',
        'yunda'=>'韵达快递',
        'zhongtong'=>'中通快递',
        'shentong'=>'申通快递',
        'huitongkuaidi'=>'百世快递',
        'shunfeng'=>'顺丰速运',
        'youzhengguonei'=>'邮政快递包裹',
        'ems'=>'EMS',
        'jd'=>'京东物流',
        'jtexpress'=>'极兔速递',
        'youzhengbk'=>'邮政标准快递',
        'debangwuliu'=>'德邦',
        'debangkuaidi'=>'德邦快递',
        'yuantongkuaiyun'=>'圆通快运',
        'youshuwuliu'=>'优速快递',
        'zhaijisong'=>'宅急送',
        'yundakuaiyun'=>'韵达快运',
        'baishiwuliu'=>'百世快运',
        'zhongtongkuaiyun'=>'中通快运',
        'zhongtongguoji'=>'中通国际',
    ];


    public static function check100($com,$num)
    {
        //====================================
        // 实时查询示例代码
        // 授权信息可通过链接查看：https://api.kuaidi100.com/manager/page/myinfo/enterprise
        //====================================

        //参数设置
        $key = Config::wechat('logistics','key');                        //客户授权key
        $customer = Config::wechat('logistics','customer');                   //查询公司编号
        $param = array (
            'com' => $com,             //快递公司编码
            'num' => $num,     //快递单号sf1434423403505
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );

        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);

        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址

        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);

        $result = self::request($url,$post_data);
        if(empty($result)){
            return [];
        }elseif(isset($result['result']) && !$result['result']){
            throw new \Exception($result['message']);
        }else{
            return empty($result['data']) ? [] : $result['data'];
        }
//        return empty($result)?[]:$result;

    }


    public static function request($url,$post_data){

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result,true);
        return $data;

    }
}